//index.js
const app = getApp();
import * as Request from '../../request';
import * as mouble from '../../until';
import store from "../../factory"
let that = null;

Page({
  data: {
  },

  onLoad: function () {
    that = this;
    that.getLoginCode()
  },
  onShow() {

  },
  getLoginCode() {
    wx.login({
      success: function (res) {
        console.log(res.code)
        store.set('loginCode', res.code);
      }
    })
  },
  getPhoneNumber(e) {
    console.log(e.detail)
    if (e && e.detail && e.detail.encryptedData) {
      that.startVerify(e.detail.encryptedData, e.detail.iv, 2)
    }
  },
  getStaffPhoneNumber(e) {
    if (e && e.detail && e.detail.encryptedData) {
      that.startVerify(e.detail.encryptedData, e.detail.iv, 1)
    }
  },
  startVerify(encryptedData, iv, type) { // 开始登陆
    wx.showLoading({
      title: '登录中...'
    });
    that.userLogin(encryptedData, iv, type)
  },
  userLogin(encryptedData, iv, type) {
    const APPDATA = that.data; // 实例数据
    // 用户登录事件
    Request.wxLogin({
      encryptedData: encryptedData,
      iv: iv,
      code: store.get("loginCode"),
      userType: type
    }).then(res => {
      wx.hideLoading()
      if (res.code == 200) {
        store.set("openId", res.data.openid)
        store.set("token", res.data.token)
        store.set("userType", type)
        wx.navigateBack({
          delta: 1 //返回的页面数，如果 delta 大于现有页面数，则返回到首页,
        });
      } else {
        if (res.code == 999) {
          that.getLoginCode()
        }
        mouble.wxErrorTips(res.message)
      }
    }).catch(err => {
      wx.hideLoading();
    })
  }

})
